import IconTable from "@/components/IconTable";
import { InfoCircleOutlined, PlusOutlined } from "@ant-design/icons";
import { DragSortTable, PageContainer } from "@ant-design/pro-components";
import {
  Button,
  Card,
  Drawer,
  Empty,
  Form,
  Input,
  Space,
  Spin,
  Tooltip,
  Image,
  Radio,
  Popconfirm,
  message,
  Modal,
} from "antd";
import { FC, useEffect, useRef, useState } from "react";
import { history, useParams } from "umi";
import SelectSearch from "@/components/SelectSearch";
import { calcColumns2 } from "./configFile";
import Https from "@/utils/Https";
import { urlReg } from "@/utils/regExp";
const TemplateDetails: FC<any> = () => {
  const { id } = useParams();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [open, setOpen] = useState(false);
  const [openIcon, setOpenIcon] = useState(false);
  const [linkPicUrl, setLinkPicUrl] = useState("");
  const [hasIcon, setHasIcon] = useState(false);
  const [type, setType] = useState("1");
  const [examId, setExamId] = useState("");
  const actionRef = useRef();
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  //获取模板详情
  const getDetails = async () => {
    setLoading(true);
    let res: any = await Https.post(
      "/merchant/bookclassflowtemplate/templateDetail",
      { id },
      true
    );
    setLoading(false);
    if (res.code == 200 && res.data) {
      form.setFieldsValue({ templateName: res.data.templateName });
    } else {
      message.error(res.msg);
    }
  };
  //获取模板流程列表
  const getList = async () => {
    let res: any = await Https.post(
      "/merchant/bookclassflowtemplate/linkAllList",
      { scheduleCourseTemplateId: id },
      true
    );
    if (res.code == 200 && res.data) {
      setData(res.data);
    }
  };
  //新增编辑步骤
  const submitForm = async () => {
    const result = await form1.validateFields();
    let params = {
      examId,
      scheduleCourseTemplateId: id,
      ...result,
    };
    setLoading(true);
    let url = result.id
      ? "/merchant/bookclassflowtemplate/updateLink"
      : "/merchant/bookclassflowtemplate/addLink";
    let res: any = await Https.post(url, params, true);
    setLoading(false);
    if (res.code == 200) {
      message.success("操作成功");
      setOpen(false);
      getList();
    } else {
      message.error(res.msg);
    }
  };
  //删除步骤
  const deleteItem = async (id, index) => {
    setLoading(true);
    let res = await Https.post(
      "/merchant/bookclassflowtemplate/deleteLink?id=" + id,
      {},
      true
    );
    setLoading(false);
    if (res.code == 200) {
      message.success("删除成功");
      let obj = [...data];
      obj.splice(index, 1);
      setData(obj);
    } else {
      message.error(res.msg);
    }
  };
  //操作列表
  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    align: "center",
    hideInSearch: true,
    render: (id, record, index) => {
      return (
        <Space>
          <Button
            type="link"
            onClick={() => {
              form1.resetFields();
              form1.setFieldsValue(record);
              setType(record.clickJump);
              setExamId(record.examId);
              setLinkPicUrl(record.linkPicUrl);
              setOpen(true);
              setHasIcon(false);
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除吗?"
            onConfirm={() => {
              deleteItem(record.id, index);
            }}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      );
    },
  };
  //排序
  const handleDragSortEnd = async (
    beforIndex,
    afterIndex,
    newDataSource: any
  ) => {
    let objList = [];
    newDataSource.map((item, index) => {
      objList.push({ id: item.id, displaySort: index });
    });
    let res = await Https.post(
      "/merchant/bookclassflowtemplate/updateLinkSort",
      objList,
      true
    );
    if (res.code == 200) {
      message.success("操作成功");
      setData(newDataSource);
    } else {
      message.error(res.msg);
    }
  };
  useEffect(() => {
    getDetails();
    getList();
  }, []);
  //修改模板信息
  const save = async () => {
    let result = await form.validateFields();
    setLoading(true);
    let res: any = await Https.post(
      "/merchant/bookclassflowtemplate/updateTemplate",
      { id, templateName: result.templateName },
      true
    );
    setLoading(false);
    if (res.code == 200) {
      message.success("操作成功");
      history.push("/system/class");
    } else {
      message.error(res.msg);
    }
  };
  return (
    <Spin spinning={loading}>
      <PageContainer
        title="模板详情"
        onBack={() => {
          history.push("/system/class");
        }}
        footer={[
          <Space key="Space">
            <Button
              key="cancel"
              onClick={() => {
                history.push("/system/class");
              }}
              size="large"
            >
              取消
            </Button>
            <Button
              type="primary"
              size="large"
              key="save"
              style={{ marginLeft: "20px" }}
              onClick={() => {
                save();
              }}
            >
              提交
            </Button>
          </Space>,
        ]}
      >
        <Card title="基础信息">
          <Form form={form}>
            <Form.Item
              label="模版名称"
              name="templateName"
              style={{ width: "30%" }}
              rules={[{ required: true, message: "模版名称不能为空" }]}
            >
              <Input placeholder="请输入模版名称" />
            </Form.Item>
          </Form>
        </Card>
        <Card
          title={
            <span>
              步骤信息
              <Tooltip placement="top" title={"预约步骤最多可新增10条"}>
                <InfoCircleOutlined style={{ marginLeft: "10px" }} />
              </Tooltip>
            </span>
          }
          extra={
            <Button
              disabled={data.length == 10}
              icon={<PlusOutlined />}
              onClick={() => {
                setOpen(true);
                form1.resetFields();
                setType("1");
                setExamId("");
                setLinkPicUrl("");
                setHasIcon(false);
              }}
              type="link"
            >
              新增步骤
            </Button>
          }
          style={{ marginTop: "20px" }}
        >
          {data.length > 0 && (
            <DragSortTable
              actionRef={actionRef}
              rowKey="id"
              scroll={{ y: 500 }}
              search={false}
              options={false}
              pagination={false}
              dragSortKey="sort"
              onDragSortEnd={handleDragSortEnd}
              dataSource={data}
              columns={calcColumns2({ operate })}
            />
          )}
          {data.length == 0 && (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={<div>暂无数据</div>}
            />
          )}
        </Card>
        <Modal
          open={open}
          title="新建步骤"
          forceRender
          destroyOnClose={true}
          maskClosable={true}
          width="40%"
          onCancel={() => setOpen(false)}
          footer={
            <Space>
              <Button onClick={() => setOpen(false)}>取消</Button>
              <Button onClick={submitForm} loading={loading} type="primary">
                确定
              </Button>
            </Space>
          }
        >
          {open && (
            <Form form={form1} labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
              <Form.Item name="id" hidden>
                <Input />
              </Form.Item>
              <Form.Item
                label="步骤名称"
                name="linkName"
                rules={[{ required: true, message: "步骤名称不能为空" }]}
              >
                <Input type="text" placeholder="请输入步骤名称" maxLength={4} />
              </Form.Item>
              <Form.Item
                label="图标"
                name="linkPicUrl"
                rules={[{ required: true, message: "图标不能为空" }]}
              >
                {linkPicUrl && (
                  <Image src={linkPicUrl} width={40} height={40} />
                )}
                <a
                  onClick={() => {
                    setOpenIcon(true);
                  }}
                  style={{ marginLeft: "10px" }}
                >
                  选择图标
                </a>
              </Form.Item>
              <Form.Item
                label="跳转类型"
                name="clickJump"
                rules={[{ required: true, message: "请选择跳转类型" }]}
              >
                <Radio.Group
                  onChange={(e) => {
                    let { value } = e.target;
                    setType(value);
                  }}
                >
                  <Radio value="1">无跳转</Radio>
                  <Radio value="3">考试</Radio>
                  <Radio value="2">外部链接</Radio>
                </Radio.Group>
              </Form.Item>
              {type == "3" && (
                <Form.Item
                  label="选择试卷"
                  name="examName"
                  rules={[{ required: true, message: "请选择试卷" }]}
                >
                  <SelectSearch
                    onSuccess={(e) => {
                      console.log(e);
                      form1.setFieldsValue({ examName: e.examName });
                      setExamId(e.id);
                    }}
                    params={{ status: "0" }}
                    url="/content/exam/list"
                    conditon="examName"
                  />
                </Form.Item>
              )}
              {type == "2" && (
                <Form.Item
                  label="链接地址"
                  name="pointLink"
                  rules={[
                    { required: true, message: "请输入链接地址" },
                    {
                      pattern: urlReg,
                      message: "请输入正确格式的链接地址",
                    },
                  ]}
                >
                  <Input type="text" placeholder="请输入链接地址" />
                </Form.Item>
              )}
            </Form>
          )}
          <Modal
            open={openIcon}
            title="选择图标"
            forceRender
            destroyOnClose={true}
            maskClosable={true}
            width="60%"
            onCancel={() => setOpenIcon(false)}
            onOk={() => {
              if (linkPicUrl && hasIcon) {
                form1.setFieldsValue({ linkPicUrl });
                setOpenIcon(false);
              } else {
                message.error("请选择图标");
              }
            }}
          >
            {openIcon && (
              <IconTable
                onSuccess={(e) => {
                  setLinkPicUrl(e);
                  setHasIcon(true);
                }}
              ></IconTable>
            )}
          </Modal>
        </Modal>
      </PageContainer>
    </Spin>
  );
};
export default TemplateDetails;
